'use client'

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
    Card,
    Descriptions,
    Tag,
    Spin,
    Alert,
    Breadcrumb,
    Button
} from 'antd';
import {
    ArrowLeftOutlined,
    BarChartOutlined,
    InfoOutlined
} from '@ant-design/icons';
import {
    BarChart,
    Bar,
    XAxis,
    YAxis,
    CartesianGrid,
    Tooltip,
    ResponsiveContainer
} from 'recharts';

import styles from './index.module.css';
import { fetchDashboardItem } from '@/lib/service/dashboard';
import { DashboardItem } from '@/lib/service/dashboard'


export default function DetailPage() {
    const params = useParams();
    const router = useRouter();
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [detail, setDetail] = useState<DashboardItem | null>(null);

    // 获取详情数据
    useEffect(() => {

        const getDetail = async () => {
            if (params.id) {
                try {
                    const detail = await fetchDashboardItem({ id: params.id as string });
                    setDetail(detail);
                } catch (error) {
                    console.error('获取数据失败:', error);
                } finally {
                    setLoading(false)
                }
            } else {
                // 处理 id 不存在的情况（比如显示错误提示）
                console.error('id 参数不存在');
            }
        }
        getDetail()

    }, [params.id]);


    // 返回按钮点击事件
    const handleBack = () => {
        router.back();
    };

    // 渲染状态标签
    const renderStatusTag = (status: DashboardItem['status']) => (
        <Tag color={status === 'active' ? 'green' : 'red'} icon={<InfoOutlined />}>
            {status === 'active' ? '已启用' : '已停用'}
        </Tag>
    );

    if (loading) {
        return (
            <div className={styles.container}>
                {/* 包裹模式：Spin直接包裹需要加载的内容区域 */}
                <Spin tip="加载详情中..." spinning={loading}>
                    <div style={{ minHeight: 600 }}>
                        {/* 骨架占位区域，保持布局稳定 */}
                        <div className={styles.header} style={{ height: 40 }}></div>
                        <div className={styles.infoCard} style={{ height: 300, marginBottom: 24 }}></div>
                        <div className={styles.chartCard} style={{ height: 450 }}></div>
                    </div>
                </Spin>
            </div>
        );
    }

    if (error || !detail) {
        return (
            <div className={styles.errorContainer}>
                <Alert
                    message="错误提示"
                    description={error || '未找到相关数据'}
                    type="error"
                    showIcon
                    action={
                        <Button onClick={() => window.location.reload()}>刷新</Button>
                    }
                />
            </div>
        );
    }

    return (
        <div className={styles.container}>
            {/* 面包屑导航 */}
            <Breadcrumb
                className={styles.breadcrumb}
                items={[
                    {
                        title: '仪表盘',
                        onClick: () => router.push('/dashboard'), // 点击跳转
                    },
                    {
                        title: "详情页面", // 当前页面标题（无点击事件）
                    },
                ]}
            />

            {/* 标题栏 */}
            <div className={styles.header}>
                <Button
                    icon={<ArrowLeftOutlined />}
                    onClick={handleBack}
                    className={styles.backButton}
                >
                    返回
                </Button>
                <h1 className={styles.title}>{detail.name}</h1>
                {renderStatusTag(detail.status)}
            </div>

            {/* 基本信息卡片 */}
            <Card className={styles.infoCard}>
                <Descriptions column={{ xs: 1, sm: 2, md: 3, lg: 3, xl: 3, xxl: 3 }}>
                    <Descriptions.Item label="ID">{detail.id}</Descriptions.Item>
                    <Descriptions.Item label="类型">{detail.type}</Descriptions.Item>
                    <Descriptions.Item label="所属模块">{detail.module}</Descriptions.Item>
                    <Descriptions.Item label="创建时间">{detail.createTime}</Descriptions.Item>
                    <Descriptions.Item label="更新时间">{detail.updateTime}</Descriptions.Item>
                    <Descriptions.Item label="创建人">{detail.creator}</Descriptions.Item>
                    <Descriptions.Item label="描述" span={3}>
                        <p className={styles.description}>{detail.description}</p>
                    </Descriptions.Item>
                </Descriptions>
            </Card>

            {/* 统计图表卡片 */}
            <Card className={styles.chartCard} title="数据统计分析">
                <div className={styles.chartContainer}>
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart
                            data={detail.stateData}
                            margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
                        >
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="name" axisLine={false} tickLine={false} />
                            <YAxis axisLine={false} tickLine={false} />
                            <Tooltip
                                contentStyle={{
                                    borderRadius: '6px',
                                    boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)',
                                    border: 'none'
                                }}
                                formatter={(value: number, name: string) => [
                                    name === 'value' ? `${value} 次` : `${value}%`,
                                    name === 'value' ? '访问量' : '完成率'
                                ]}
                            />
                            <Bar
                                dataKey="value"
                                fill="#1677ff"
                                radius={[4, 4, 0, 0]}
                                name="访问量"
                            />
                            <Bar
                                dataKey="percentage"
                                fill="#40a9ff"
                                radius={[4, 4, 0, 0]}
                                name="完成率"
                            />
                        </BarChart>
                    </ResponsiveContainer>
                </div>
                <div className={styles.chartLegend}>
                    <div className={styles.legendItem}>
                        <span className={styles.legendColor} style={{ backgroundColor: '#1677ff' }}></span>
                        <span>访问量</span>
                    </div>
                    <div className={styles.legendItem}>
                        <span className={styles.legendColor} style={{ backgroundColor: '#40a9ff' }}></span>
                        <span>完成率(%)</span>
                    </div>
                </div>
            </Card>
        </div>
    );
}
